﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MakeItWeb.Framework;
using System.Security;
using System.Configuration;
using System.Collections.Specialized;

namespace AllNations.WebAppAdmin
{
    public partial class EditPage : MakeItWebAdminPage
    {
        HtmlPage _HtmlPage;

        private HtmlPage EditHtmlPage
        {
            get
            {
                if (_HtmlPage == null)
                {
                    _HtmlPage = HtmlPage.GetPageDetailById(new Guid(Request.QueryString["HtmlPageId"]));

                    if (_HtmlPage == null)
                        throw new SecurityException("Invalid page.");
                }
                return _HtmlPage;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (EditHtmlPage == null)
                throw new SecurityException("Invalid page.");

            string sPageUrl = string.Format("~{0}", EditHtmlPage.PageUrl.Substring(0, EditHtmlPage.PageUrl.IndexOf("?") == -1 ? EditHtmlPage.PageUrl.Length : EditHtmlPage.PageUrl.IndexOf("?")));
            //MakeItWebPage miwPage = System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(sPageUrl, typeof(MakeItWebPage)) as MakeItWebPage;
            //IDynamicPage dynamicPage = PreviousPage as IDynamicPage;
            string sPageTypeFromUrl = GetPageTypeFromUrl(sPageUrl);


            if (string.IsNullOrEmpty(sPageTypeFromUrl))
            {
                trPageTypeConfiguration.Visible = false;
                return;
            }

            IDynamicPage dynamicPage = this.GetType().BaseType.Assembly.CreateInstance(sPageTypeFromUrl) as IDynamicPage;
            if (dynamicPage != null && !string.IsNullOrEmpty(dynamicPage.GetPageConfigurationControl()))
            {
                trPageTypeConfiguration.Visible = true;
                Control ctl = LoadControl(dynamicPage.GetPageConfigurationControl());
                lblConfigurationSectionName.Text = (ctl as IDynamicPageConfiguration).ConfigurationSectionLabel;
                if (ctl is IDynamicPageConfiguration)
                    (ctl as IDynamicPageConfiguration).LoadSettings(EditHtmlPage.PageSettings);
                pldDynamicConfiguration.Controls.Add(ctl);
            }
            else
                trPageTypeConfiguration.Visible = false;
        }

        private string GetPageTypeFromUrl(string sPageUrl)
        {
            var types = ConfigurationManager.GetSection("IDynamicPageTypes") as NameValueCollection;
            if (types != null)
                return types[sPageUrl];

            return null;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lblDefaultDescription.Text = ConfigurationManager.AppSettings["DefaultSiteDescription"];
                lblPageKeywords.Text = ConfigurationManager.AppSettings["DefaultSiteKeywords"];
                lblDefaultTitle.Text = ConfigurationManager.AppSettings["DefaultSiteTitle"];
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            EditHtmlPage.HtmlTitleTxt = txtHtmlTitle.Text.Trim();
            EditHtmlPage.PageTitleTxt = txtPageTitle.Text.Trim();
            EditHtmlPage.MetaDescriptionTxt = txtPageDescription.Text.Trim();
            EditHtmlPage.MetaKeywordTxt = txtPageKeywords.Text.Trim();
            EditHtmlPage.MetaNoarchiveInd = cbGoogleNoArchive.Checked;
            EditHtmlPage.MetaNofollowInd = cbRobotNoFollow.Checked;
            EditHtmlPage.MetaNoindexInd = cbRobotNoIndex.Checked;
            EditHtmlPage.IncludeHeaderImageInd = cbIncludeHeaderImage.Checked;
            if (fuHeaderImage.HasFile)
            {
                // save the file
                // create photoalbum file directory
                string sRoot = @"~/Images/Headers/";
                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["HeaderImageRoot"]))
                    sRoot = ConfigurationManager.AppSettings["HeaderImageRoot"];
                string sRootPath = HttpContext.Current.Server.MapPath(sRoot);
                if (!System.IO.Directory.Exists(sRootPath))
                    System.IO.Directory.CreateDirectory(sRootPath);

                string sFileName = string.Format("{0}.{1}", Guid.NewGuid(), fuHeaderImage.FileName.Substring(fuHeaderImage.FileName.LastIndexOf(@".") + 1));
                fuHeaderImage.SaveAs(string.Format(@"{0}\{1}", sRootPath, sFileName));
                EditHtmlPage.HeaderImageUrl = string.Format("{0}{1}", sRoot, sFileName);
            }
            if (trPageTypeConfiguration.Visible)
                EditHtmlPage.PageSettings = (pldDynamicConfiguration.Controls[0] as IDynamicPageConfiguration).SaveSettings();
            EditHtmlPage.Save();

            Response.Redirect(EditHtmlPage.PageUrl, true);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            lblPageUrl.Text = EditHtmlPage.RoutedPageUrl ?? EditHtmlPage.PageUrl;
            txtHtmlTitle.Text = EditHtmlPage.HtmlTitleTxt;
            txtPageTitle.Text = EditHtmlPage.PageTitleTxt;
            txtPageDescription.Text = EditHtmlPage.MetaDescriptionTxt;
            txtPageKeywords.Text = EditHtmlPage.MetaKeywordTxt;
            cbGoogleNoArchive.Checked = EditHtmlPage.MetaNoarchiveInd;
            cbRobotNoFollow.Checked = EditHtmlPage.MetaNofollowInd;
            cbRobotNoIndex.Checked = EditHtmlPage.MetaNoindexInd;
            cbIncludeHeaderImage.Checked = EditHtmlPage.IncludeHeaderImageInd;
            if (!string.IsNullOrEmpty(EditHtmlPage.HeaderImageUrl))
                imgHeaderImage.ImageUrl = EditHtmlPage.HeaderImageUrl;
            else
                imgHeaderImage.ImageUrl = "~/Images/genericPageHeader.png";
        }
    }
}